from google.appengine.ext import db

from lib.webapp import app, render_context, render, MJRequestHandler
from os.path import join

import lib.waypoints as wp

import sys
import logging

#from django import forms
from django import newforms as forms


from lib.webapp import app, check_admin

log = logging.getLogger(__name__)

class RegionForm( forms.Form ):
    
    region          = forms.CharField(widget=forms.HiddenInput(),required=False)
    name            = forms.CharField(max_length=60,required=True)
    desc            = forms.CharField(max_length=512,widget=forms.Textarea(attrs={'rows':'10','cols':'70'}),required=False)
    region_parent   = forms.CharField(widget=forms.HiddenInput(),required=False)

class ctl_Regions(MJRequestHandler):
 
    path = "/regions"
 

    def load_region_parent(self):
      
        region = self.request.get( "region_parent", None )
        log.debug( "region_parent = %s" % region )

        if( None == region  ):
            self.redirect( "/error?msg=no_region_parent_key" )
            
            return False
            
        try:
            self.c.region_parent = db.GqlQuery( "select * from Region where __key__ = :1", db.Key(region)  ).fetch(1)[0]
            log.debug( "loaded prent region for %s" % region )
        except:
            self.redirect( "/error?msg=wrng_region_key" )
            return False

        return True      
 


    def load_region(self):
      
        region = self.request.get( "region", None )
        log.debug( "regions = %s" % region )

        if( None == region  ):
            self.redirect( "/error?msg=no_regions_key" )
            
            return False
            
        try:
            self.c.region = db.GqlQuery( "select * from Region where __key__ = :1", db.Key(region)  ).fetch(1)[0]
            log.debug( "loaded region for %s" % region )
        except:
            self.redirect( "/error?msg=wrng_region_key" )
            return False

        return True      
 
    @check_admin
    def save(self):
        
        self.c.form = RegionForm( self.request )
        
        if( self.c.form.is_valid() ):

            region_key = self.c.form.clean_data["region"]
            parent_region_key = self.c.form.clean_data["region_parent"]

            region = None
            
            if( region_key != "" ):
                if( not self.load_region() ):
                    return None

                self.c.region.name = self.c.form.clean_data["name"]

            else:        
                self.c.region = wp.Region(name=self.c.form.clean_data["name"])

            if( parent_region_key != "" ):
                if( not self.load_region_parent() ):
                    return None
                else:
                    if( self.c.region_parent.level >= 4 ):
                        self.redirect( "/error?msg=Too deep, more then 4 levels of depth!" )
                        return
                    self.c.region.parent_region = self.c.region_parent
                    self.c.region.level = self.c.region_parent.level + 1

            self.c.region.desc = self.c.form.clean_data["desc"]
                
            self.c.region.put()
            self.redirect_index()
        else:
            return self.render( "/en/editregion.html" )  
              
      
    @check_admin
    def edit(self):
        
        #load region
        if( self.load_region() ):
            log.debug( "edit a region" )
            self.c.form = RegionForm({\
                "name":self.c.region.name,\
                "desc":self.c.region.desc, \
                "region":self.c.region.key() } )
        else:
            self.redirect_index()
            return

        return self.render( "/en/editregion.html" )  

    @check_admin
    def new(self):
        self.c.form = RegionForm(self.request)    
        return self.render( "/en/editregion.html" )  

    def view(self):

        if( not self.load_region() ):
            return self.redirect_index()

        self.c.regions = dict()
      
        def add_r( region ):
            if( region == None ):
                return
            self.c.regions[region.level] = region
            if( region.level > 0 ):
                add_r( region.parent_region )

        add_r( self.c.region.parent_region )
        return self.render( "/en/viewregion.html" )  

    def index(self):
      
        self.c.regions = dict()
      
        def add_r( all_index, index, region ):
        
            all_index += "%04d" % index 
            self.c.regions[all_index] = region
            si = 0
            for r in region.get_subregions():
                add_r( all_index, si, r )
                si += 1

        dbregions = wp.Region.gql( "where level = 0 order by name" )
        si = 0    
        for r in dbregions:
                add_r( "", si, r )
                si += 1

        return self.render( "/en/listregions.html" )
      

    def __init__(self):
      
        MJRequestHandler.__init__(self)
      
        self.add_handler( "/save", self.save )
        self.add_handler( "/edit", self.edit )
        self.add_handler( "/new", self.new )
        self.add_handler( "/view", self.view, False )



app().add_handler( ctl_Regions.path + ".*", ctl_Regions )
